// https://www.lintcode.com/problem/word-spacing/

public class Solution {
    /**
     * @param words: the words given.
     * @param wordA: the first word you need to find.
     * @param wordB: the second word you need to find.
     * @return: return the spacing of the closest wordA and wordB.
     */
    public int wordSpacing(List<String> words, String wordA, String wordB) {
        // write your code here.
        List<Integer> setA = new ArrayList<>();
        List<Integer> setB = new ArrayList<>();
        for (int i = 0; i < words.size(); ++i) {
            String word = words.get(i);
            if (wordA.equals(word)) {
                setA.add(i);
            } else if (wordB.equals(word)) {
                setB.add(i);
            }
        }
        if (setA.isEmpty() || setB.isEmpty()) {
            return -1;
        }
        int ret = words.size();
        for (Integer i : setA) {
            for (Integer j : setB) {
                int dist = Math.abs(j - i);
                if (dist < ret) {
                    ret = dist;
                }
            }
        }
        return ret;
    }
}